#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *

import sqlite3

from gui.ui_mainwindow import Ui_MainWindow
from quizdialog import QuizDialog

class MainWindow(QMainWindow, Ui_MainWindow):
	def __init__(self, parent = None):
		super(MainWindow, self).__init__(parent)
		self.setupUi(self)

		self._connectSlots()

	def closeEvent(self, event):
		event.accept()

	def _connectSlots(self):
		self.connect(self.listWidgetAvailable, SIGNAL("itemSelectionChanged()")
					, lambda:self.SelectionChanged(self.listWidgetAvailable, self.pushButton_moveright))
		self.connect(self.listWidgetSelected, SIGNAL("itemSelectionChanged()")
					, lambda:self.SelectionChanged(self.listWidgetSelected, self.pushButton_moveleft))

		self.connect(self.pushButton_moveright, SIGNAL("clicked()")
					, lambda:self.MoveButtonClicked(self.listWidgetAvailable, self.listWidgetSelected, self.pushButton_moveright, self.pushButton_moveleft))
		self.connect(self.pushButton_moveleft, SIGNAL("clicked()")
					, lambda:self.MoveButtonClicked(self.listWidgetSelected, self.listWidgetAvailable, self.pushButton_moveleft, self.pushButton_moveright))
		
		self.connect(self.pushButton, SIGNAL("clicked()")
#					, lambda:self.PrintList(self.listWidgetAvailable))
					, self.OpenQuizDialog)

		self.connect(self.actionLoad_from_DB, SIGNAL('triggered()'), self.OpenFileDialog)
		self.connect(self.actionExit, SIGNAL('triggered()'), SLOT('close()'))

#			QMessageBox.critical(self, "Error", "Not connected to a server.")
	
	def SelectionChanged(self, lw, b):
		if lw.selectedItems():
			b.setEnabled(True)
		else:
			b.setEnabled(False)


	def MoveButtonClicked(self, lw_from, lw_to, button_from, button_to):
		for i in lw_from.selectedItems():
			item = lw_from.takeItem(lw_from.row(i))
			lw_to.addItem(item)

		if lw_from.selectedItems() == []:
			button_from.setEnabled(False)

	def PrintList(self, lw):
		for i in xrange(lw.count()):
			print lw.item(i).text()

	def OpenQuizDialog(self):
		dialog = QuizDialog(self, nquestions = self.spinBox.value())
		dialog.show()
		if dialog.exec_() == QDialog.Accepted:
			print dialog.curquestion

	def OpenFileDialog(self):
		filename = QFileDialog.getOpenFileName(self, 'Open file', '.')
		conn = sqlite3.connect(str(filename))
		c = conn.cursor()
		c.execute('select theme, serno from themes')
		for rec in c:
			self.listWidgetAvailable.addItem(rec[0])
#			print str(rec)
		c.close()
#		print unicode(filename)
#		fname = open(filename)
#		data = fname.read()
#		
#		self.textEdit.setText(data)

